﻿namespace CacheProviderEntities
{
    #region N A M E S P A C E   I M P O R T S

    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;

    #endregion

    public class CacheDBCommandHelper
    {
        public static void PersistDBCommandParamters(DependencyInfo dependencyInfo)
        {
            dependencyInfo.DbCommandInfos = new List<DBCommandInfo>();
            foreach (var dbCommand in dependencyInfo.DbCommands)
            {
                var dbCommandInfo = new DBCommandInfo
                {
                    StoredProcedureName = dbCommand.CommandText,
                    Parameters = new List<Tuple<string, string>>()
                };
                if (dependencyInfo.CacheDependencyType == CacheDependencyTypes.SQLDependency)
                    foreach (SqlParameter parameter in dbCommand.Parameters)
                    {
                        dbCommandInfo.Parameters.Add(new Tuple<string, string>(parameter.ParameterName, parameter.Value.ToString()));
                    }

                dependencyInfo.DbCommandInfos.Add(dbCommandInfo);
            }
        }

        public static void RestoreDBCommandParameters(DependencyInfo dependencyInfo)
        {
            if (dependencyInfo.DbCommandInfos == null)
                return;

            var dbCommands = new List<DbCommand>();
            foreach (var dbCommandInfo in dependencyInfo.DbCommandInfos)
            {
                var dbCommand = new SqlCommand
                {
                    CommandText = dbCommandInfo.StoredProcedureName,
                    CommandType = CommandType.StoredProcedure
                };
                if (dbCommandInfo.Parameters == null) continue;

                foreach (var sqlParameter in dbCommandInfo.Parameters)
                {
                    dbCommand.Parameters.Add(new SqlParameter(sqlParameter.Item1, sqlParameter.Item2));
                }

                dbCommands.Add(dbCommand);
            }

            dependencyInfo.DbCommands = dbCommands;
        }
    }
}
